/*
 * TCPSocketSSL.cpp
 *
 *  Created on: 2011-3-5
 *      Author: lionxing
 */

#include "TCPSocketSSL.h"
#include <charconv.h>
#include <EIKENV.H> 
#include <e32des16.h>	
#include <UTF.H> 

// CONSTANTS
const TInt KTimeout = 10;

CTCPSocketSSL* CTCPSocketSSL::NewL(MObserver& aObserver, RSocket& aSocket)
{
	CTCPSocketSSL* self = new(ELeave) CTCPSocketSSL(aObserver, aSocket);
	CleanupStack::PushL(self);
	self->ConstructL();
	CleanupStack::Pop();
	return self;
}

CTCPSocketSSL::CTCPSocketSSL(MObserver& aObserver, RSocket& aSocket) : 
CActive(EPriorityStandard), iObserver(aObserver), iSocket(aSocket)	// Standard priority
{
	CActiveScheduler::Add(this);
}

void CTCPSocketSSL::ConstructL()
{
	iSSLSocket = CSecureSocket::NewL( iSocket, _L("TLS1.0"));
 
	iSSLSocket->FlushSessionCache();
	iSSLSocket->SetOpt(KSoSSLDomainName,KSolInetSSL, _L8("talk.google.com") );    
    // start the handshake 
	iSSLSocket->StartClientHandshake( iStatus );
	
	iSSLRev = new(ELeave)CTCPSocketSSLRev(*this,iSSLSocket);
	iSSLSend = CTCPSocketSSLSender::NewL(*this,iSSLSocket);
	
	SetActive();
}

CTCPSocketSSL::~CTCPSocketSSL()
{

	Cancel();
	delete iSSLRev;
	delete iSSLSend;
	if(iSSLSocket)
	{
		delete iSSLSocket;
		iSSLSocket = NULL;
	}
	delete iSSLSocket;
}


void CTCPSocketSSL::DoCancel()
{
	 iSSLSocket->CancelAll();
}

void CTCPSocketSSL::RunL()
{
	if(iStatus.Int() == KErrNone)
    {
		iSSLRev->Receive();
    }
	
	iObserver.OnHandComplete(iStatus.Int());
	
}


void CTCPSocketSSL::OnReceiveSSL(const TDesC8& aData, TInt aError) 
{
	iObserver.OnRevSSL(aData,aError);
}

void CTCPSocketSSL::OnSendSSL(const TDesC8& aMsg, TInt aError) 
{
	iObserver.OnSendSSL(aMsg,aError);
}


void CTCPSocketSSL::SendSSL(const TDesC8& des)
{
	
	if(iSSLSend)
	{
		iSSLSend->Send(des);
	}
}


void CTCPSocketSSL::RevSSL()
{
	if(iSSLRev)
	{
		iSSLRev->Receive();
	}
}
